package com.eims.hongbao.fragment;

import java.text.DecimalFormat;

import com.android.volley.toolbox.RequestParams;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.ui.MainFaHongbaoActivity;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.BaseHelper;
import com.eims.sls_app.utils.NetWork;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import bls.juejin.cn.R;
import progressBar.ProgressDialogBar;

public class HongbaoOneFragment extends Fragment implements OnClickListener {
    private static final String TAG = "HongbaoOneFragment";
    private Activity activity;
    private EditText etMoneyNum, etDes, etPeopleNum, etLimitNum;

    private Button btnPayMoney;
    private String schemeid;

    private MyHandler myHandler;

    private String opt, auth, info, time, imei, crc; // 格式化后的参数

    private ProgressDialog pd;

    private String totalNum;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.hongbao_one_fragment, container, false);
        activity = getActivity();
        Bundle args = getArguments();
        if (args != null) {
            this.schemeid = args.getString("schemeid");
        }

        myHandler = new MyHandler();
        init(view);
        return view;
    }


    public HongbaoOneFragment() {
        super();
    }

    public static HongbaoOneFragment newInstance(String schemeid) {

        Bundle args = new Bundle();

        HongbaoOneFragment fragment = new HongbaoOneFragment();
        args.putString("schemeid", schemeid);
        fragment.setArguments(args);
        return fragment;
    }

    private void init(View view) {
        // TODO Auto-generated method stub

        etMoneyNum = (EditText) view.findViewById(R.id.et_num);
        etDes = (EditText) view.findViewById(R.id.et_des);
        btnPayMoney = (Button) view.findViewById(R.id.btn_pay_money);
        btnPayMoney.setOnClickListener(this);
        etPeopleNum = (EditText) view.findViewById(R.id.et_people_num);
        etLimitNum = (EditText) view.findViewById(R.id.et_limt_num);

        etPeopleNum.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                getMoney(etMoneyNum.getText().toString());
            }

        });
        etMoneyNum.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0, s.toString().indexOf(".") + 3);
                        etMoneyNum.setText(s);
                        etMoneyNum.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    etMoneyNum.setText(s);
                    etMoneyNum.setSelection(2);
                }

                if (s.toString().startsWith("0") && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        etMoneyNum.setText(s.subSequence(0, 1));
                        etMoneyNum.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                getMoney(etMoneyNum.getText().toString());
            }

        });
        etLimitNum.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0, s.toString().indexOf(".") + 3);
                        etLimitNum.setText(s);
                        etLimitNum.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    etLimitNum.setText(s);
                    etLimitNum.setSelection(2);
                }

                if (s.toString().startsWith("0") && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        etLimitNum.setText(s.subSequence(0, 1));
                        etLimitNum.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }

        });

    }

    public void getMoney(String string) {
        // TODO Auto-generated method stub
        if (string != null && !"".equals(string)) {

            if (etPeopleNum.getText().toString() != null && !"".equals(etPeopleNum.getText().toString())) {
                Double num = Double.parseDouble(string);
                Double hongbaoNum = Double.parseDouble(etPeopleNum.getText().toString());

                DecimalFormat df = new DecimalFormat("######0.00");
                String decimalBalanceString = df.format(num * hongbaoNum);// format 返回的是字符


                if (num == 0) {
                    totalNum = "";
                    btnPayMoney.setText("塞钱");
                } else {
                    btnPayMoney.setText("塞钱 " + decimalBalanceString + "元");
                    totalNum = decimalBalanceString;
                }
            } else {
                totalNum = "";
                btnPayMoney.setText("塞钱");
            }


        } else {
            totalNum = "";
            btnPayMoney.setText("塞钱");
        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.btn_pay_money:

                btnPayMoney.setEnabled(false);

                if (etPeopleNum.getText().toString() != null && !"".equals(etPeopleNum.getText().toString())) {

                    int peoplenum = Integer.parseInt(etPeopleNum.getText().toString());
                    if (peoplenum == 0) {
                        btnPayMoney.setEnabled(true);

                        Toast.makeText(activity, "红包个数不能为零", Toast.LENGTH_SHORT).show();
                    } else {

                        if (etMoneyNum.getText().toString() != null && !"".equals(etMoneyNum.getText().toString())) {
                            Double num = Double.parseDouble(etMoneyNum.getText().toString());
                            DecimalFormat df = new DecimalFormat("######0.00");
                            String decimalBalanceString = df.format(num) + "";// format 返回的是字符
                            if (num == 0) {
                                btnPayMoney.setEnabled(true);
                                Toast.makeText(activity, "金额不能为零", Toast.LENGTH_SHORT).show();
                            } else if (num < 0.1) {
                                btnPayMoney.setEnabled(true);
                                Toast.makeText(activity, "金额不能小于0.1", Toast.LENGTH_SHORT).show();
                            } else if (num > 200) {
                                btnPayMoney.setEnabled(true);
                                Toast.makeText(activity, "金额不要大于200", Toast.LENGTH_SHORT).show();
                            } else {
                                if (etLimitNum.getText().toString() != null
                                        && !"".equals(etLimitNum.getText().toString())) {

                                    if (Double.parseDouble(etLimitNum.getText().toString()) > 0) {
                                        if (Double.parseDouble(App.user.getBalance()) < Double
                                                .parseDouble(totalNum)) {
                                            Toast.makeText(activity, "您的余额已不足，请及时充值！", Toast.LENGTH_SHORT).show();
                                        } else {
                                            if (NetWork.isConnect(activity)) {
                                                btnPayMoney.setClickable(false);

                                                btnPayMoney.setEnabled(false);
                                                pd = BaseHelper.showProgress(activity, "", "加载中...", true, false);
                                                MyAsynTask asynTask = new MyAsynTask();
                                                asynTask.execute();

                                            } else {
                                                btnPayMoney.setEnabled(true);
                                                Toast.makeText(activity, "网络连接错误", Toast.LENGTH_SHORT).show();
                                            }
                                        }

                                    } else {
                                        btnPayMoney.setEnabled(true);
                                        Toast.makeText(activity, "可抢金额不能为0！", Toast.LENGTH_SHORT).show();

                                    }

                                } else {
                                    btnPayMoney.setEnabled(true);

                                    Toast.makeText(activity, "请设置可抢金额！", Toast.LENGTH_SHORT).show();
                                }

                            }

                        } else {
                            btnPayMoney.setEnabled(true);
                            Toast.makeText(activity, "金额不能为空！", Toast.LENGTH_SHORT).show();
                        }
                    }
                } else {
                    btnPayMoney.setEnabled(true);
                    Toast.makeText(activity, "请输入红包个数", Toast.LENGTH_SHORT).show();
                }
                break;

            default:
                break;
        }
    }

    class MyAsynTask extends AsyncTask<Integer, Integer, String> {

        String error = "-1";

        @Override
        protected String doInBackground(Integer... params) {

            opt = "110";//发红包
            time = RspBodyBaseBean.getTime();
            imei = RspBodyBaseBean.getIMEI(activity);

            if (!etDes.getText().toString().equals("") && etDes.getText().toString() != null) {
                info = RspBodyBaseBean.changeFaHongbao_info(totalNum, "false",
                        etPeopleNum.getText().toString(), etDes.getText().toString(), etLimitNum.getText().toString(),
                        schemeid);
            } else {
                info = RspBodyBaseBean.changeFaHongbao_info(totalNum, "false",
                        etPeopleNum.getText().toString(), "祝您中奖！！！", etLimitNum.getText().toString(), schemeid);
            }

            // String key = MD5.md5(App.user.getUserPass() + App.MD5_key);
            String key = App.key;
            crc = RspBodyBaseBean.getCrc(time, imei, key, info, App.user.getUid());
            auth = RspBodyBaseBean.getAuth(crc, time, imei, App.user.getUid());
            String[] values = {opt, auth, info};
            Log.i(TAG, "红包" + RequestParams.convertParams(activity, opt, info));
            String result = HttpUtils.doPost(App.names, values, App.path);
            System.out.println("红包：" + result);
            if (!result.equals("")) {
                if (result.equals("success")) {
                    error = "0";
                } else {

                    error = "-1";
                }

            }

            return error;
        }

        @Override
        protected void onPostExecute(String result) {

            myHandler.sendEmptyMessage(Integer.parseInt(result));

            super.onPostExecute(result);
        }
    }

    @SuppressLint("HandlerLeak")
    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            btnPayMoney.setEnabled(true);

            if (pd != null) {
                pd.dismiss();
            }
            switch (msg.what) {
                case 0:
                    // MyToast.getToast(context, "评论成功，请重新刷新").show();
                    ProgressDialogBar.startProgress(activity, "sff", false);
                    myHandler.sendEmptyMessageDelayed(3, 1000);
                    // CommentActivity.this.finish();

                    break;
                case 1:
                    // MyToast.getToast(context, "重复晒单").show();
                    // Toast.makeText(CommentActivity.this, "您未跟单此单 没评论权限",
                    // Toast.LENGTH_SHORT).show();
                    ;
                    break;
                case -2:

                    break;
                case -1:
                    btnPayMoney.setClickable(true);
                    Toast.makeText(activity, "红包发送失败！", Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    btnPayMoney.setClickable(true);
                    Toast.makeText(activity, "红包发送成功！", Toast.LENGTH_SHORT).show();
                    activity.finish();
                    break;
                case 4:
                    ProgressDialogBar.stopProgress();
                    activity.finish();
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    }
}
